package com.mz.ieann.dokit.utils

import android.os.Parcelable
import android.util.Log
import androidx.annotation.NonNull
import com.mz.ieann.dokit.sdk.SDKConstant
import okhttp3.internal.and
import java.security.MessageDigest
import java.util.*

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> des
 * <p>
 *
 * @author Created by zhangmz90
 * @date on 2021 2021/11/14 13:39
 */
object SdkUtils {

    /**
     * Parcelable 类转化 map
     */
    fun entityToMap(parcelable: Parcelable): Map<String, Any?> {
        val map: MutableMap<String, Any?> = HashMap()
        try {
            for (field in parcelable.javaClass.declaredFields) {
                val flag = field.isAccessible
                field.isAccessible = true
                val o = field[parcelable]
                if (o is Parcelable.Creator<*>) {
                    continue
                }
                map[field.name] = o
                field.isAccessible = flag
            }
        } catch (e: Exception) {
            Log.e(SDKConstant.TAG, "error: ${e.message}")
        }
        return map
    }

    /**
     * Parcelable 类转化 map
     */
    fun entityToMapString(parcelable: Parcelable): Map<String, String> {
        val map: MutableMap<String, String> = HashMap()
        try {
            for (field in parcelable.javaClass.declaredFields) {
                val flag = field.isAccessible
                field.isAccessible = true
                val o = field[parcelable] ?: continue
                if (o is Parcelable.Creator<*>) {
                    continue
                }
                map[field.name] = o.toString()
                field.isAccessible = flag
            }
        } catch (e: Exception) {
            Log.e(SDKConstant.TAG, "entityToMapString, error: ${e.message}")
        }
        return map
    }

    /**
     * md5加密
     */
    fun md5(password: String): String? {
        return runCatching {
            val sb = StringBuilder()
            val instance = MessageDigest.getInstance("MD5")
            val digest = instance.digest(password.toByteArray())
            for (b in digest) {
                // 获取到第八位有效值，加盐处理
                val i: Int = b and 0xff
                var hexString = Integer.toHexString(i)
                if (hexString.length < 2) {
                    hexString = "0$hexString"
                }
                sb.append(hexString)
            }
            sb.toString()
        }.getOrElse { password }
    }

}